package Day019_Junit单元测试_NIO.demo6_发消息;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author zhangyan
 * @date 2020/5/12 19:09
 */
public class Test1_Server {
    public static void main(String[] args) throws Exception {

        //创建ServerSocketChannel对象
        //调用ServerSocketChannel的open()方法打开通道
        ServerSocketChannel ssc = ServerSocketChannel.open();

        //绑定端口
        ssc.bind(new InetSocketAddress(666));

        //等待请求
        SocketChannel sc = ssc.accept(); // 返回的是Socket对象
        System.out.println("连接成功...");

        Scanner s = new Scanner(System.in);
        while (true) {

            // 创建ByteBuffer缓冲数组
            ByteBuffer b1 = ByteBuffer.allocate(1024);

            //读取数据
            sc.read(b1);
            //b1.flip();
            System.out.println("客户端消息:" + new String(b1.array(), 0, b1.limit()));

            //回写数据
            // 创建ByteBuffer缓冲数组
            ByteBuffer b2 = ByteBuffer.allocate(1024);
            //键盘录入
            System.out.println("输入要发送的消息:");
            String str = s.nextLine();
            if(str.equals("88")){
                break;
            }

            //数据添加到缓冲数组
            b2.put(str.getBytes());
            //切换
            b2.flip();
            //写出数据
            sc.write(b2);
        }
        sc.close();
        ssc.close();
    }
}
